<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

require_once('parser/TemplateParser.php');
require_once('helper/View_Helper.php');

/**
 *
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package Simplify_Kernel_View
 */
class View_Simplify extends View
{

  /**
   * (non-PHPdoc)
   * @see simplify2/kernel/view/IView#render($object)
   */
  public function render(IRenderable $object = null)
  {
    global $config;

    if (empty($object)) {
      $object = $this;
    }

    $template = $object->getTemplate();

    $pathinfo = pathinfo($template);
    $cache = $config['templates_cache_dir'] . '/' . $config['theme'] . '_' . $pathinfo['filename'] . '_' . Account::getLocale() . '.php';

    $modified = filemtime($template);
    $cached = @filemtime($cache);

    if (Simplify::request()->get('DISABLE_VIEW_CACHE') || $modified > $cached) {
      $output = TemplateParser::parseFile($template);
      file_put_contents($cache, $output);
    }

    $output = $this->internalRender($object, $cache);

    $layout = $object->getLayout();

    if ($layout !== false) {
      if (empty($layout)) {
        $layout = $this->defaultLayout;
      }

      $view = new self();
      $view->copyAll($object);
      $view->copyAll($this);
      $view->set('layout_content', $output);
      $view->setTemplate($layout);
      $view->setLayout(false);

      $output = $view->render();
    }

    return $output;
  }

  /**
   *
   * @param $object
   * @param $template
   * @return unknown_type
   */
  protected function internalRender(IDictionary $object, $template)
  {
    header('Content-Type: text/html; charset=UTF-8');

    extract($object->getAll(), EXTR_REFS);

    ob_start();
    require ($template);
    $output = ob_get_clean();

    return $output;
  }

}

?>